package org.xlp.db.bridge.strategy;

import org.xlp.db.sql.limit.Limit;
import org.xlp.db.xml.XmlSQL;
import org.xlp.db.xml.XmlSQLConstructorUtils;
import org.xlp.db.xml.ele.SQLEle;
import org.xlp.utils.XLPArrayUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: (Object param) : 单个其他类型参数
 * <br/>date: 2024/4/23
 *
 * @version 1.0
 * @author: xlp
 */
public class ZPXmlSQLConstructorStrategy extends AbstractXmlSQLConstructorStrategy {
    /**
     * 构造函数
     */
    public ZPXmlSQLConstructorStrategy(){
       setWeight(3);
    }

    /**
     * 根据给定的参数类型获取相应的{@link XmlSQL}的构造函数
     *
     * @param methodReturnType
     * @param parameterClasses
     * @return
     */
    @Override
    public XmlSQLConstructorInfo getXmlSQLConstructor(Type methodReturnType,
                                    Class<?>[] parameterClasses, Object[] parameters) {
        if (XLPArrayUtil.isEmpty(parameterClasses)) return null;

        int index = Finder.findClassInClasses(parameterClasses, Limit.class);

        List<Object> _parameters = new ArrayList<>();
        _parameters.add(new Object[]{parameters[index == 0 ? 1 : 0]});
        //获取实体类型
        Class<?> beanClass = getBeanClassByReturnType(methodReturnType);
        _parameters.add(beanClass);

        Class<?>[] classes = {SQLEle.class, Object[].class, Class.class};
        XmlSQLConstructorInfo info = new XmlSQLConstructorInfo();
        info.setParameters(_parameters);
        try {
            info.setConstructor(XmlSQL.class.getConstructor(classes));
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        try {
            info.setConstructor(XmlSQLConstructorUtils.getXmlSQLConstructor(classes));
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        if (index != Finder.NOT_FIND) info.setLimit((Limit) parameters[index]);
        return info;
    }
}
